package com.jp.knowledge.activity;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.ProductInterfaceRightMenuAdapter;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.fragment.ProductEvluationBaseFragment;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.ProductUIMenuModel;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.JpDiver;
import com.jp.knowledge.view.TabView;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/5/11.
 */

public class ProductEvaluationActivity extends SlidingActivity implements View.OnClickListener {

    @ViewInject(R.id.drawerLayout)
    protected DrawerLayout drawerLayout;
    @ViewInject(R.id.tab_view)
    protected TabView tabView;
    @ViewInject(R.id.sort_btn)
    protected ImageView sortBtn;
    @ViewInject(R.id.order_viewpager)
    protected ViewPager viewPager;

    @ViewInject(R.id.right_menu)
    protected LinearLayout rightMenu;
    @ViewInject(R.id.right_rv)
    protected RecyclerView rightMenuRv;

    private String rightMenuCachePath;
    private FileCacheManager cacheManager;
    private List<ProductUIMenuModel> menuModelList;
    private ProductInterfaceRightMenuAdapter rightMenuAdapter;

    protected List<Fragment> fragments;
    protected int recommendAction;
    protected int action;

    @Override
    protected int getResourceId() {
        return R.layout.activity_order;
    }

    @Override
    protected void init() {
        fragments = new ArrayList<>();
        initAction();
        initTitleBar();
        initRightMenu();
        initFragment();
        viewPager.setBackgroundColor(mContext.getResources().getColor(R.color.white));
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }
            @Override
            public int getCount() {
                return fragments.size();
            }
        });
        initTabLayout();

        try {
            int tabIndex = getIntent().getIntExtra("tabIndex", 0);
            viewPager.setCurrentItem(tabIndex);
        } catch (Exception e){

        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        try {
            int tabIndex = intent.getIntExtra("tabIndex", 0);
            viewPager.setCurrentItem(tabIndex);
        } catch (Exception e){

        }
    }

    protected void initAction(){
        action = 1;
        recommendAction = 6;
    }

    protected void initFragment(){
//        fragments.add(ProductEvluationRecommendFragment.newInstance(1, recommendAction));
        fragments.add(ProductEvluationBaseFragment.newInstance(1, action));
        fragments.add(ProductEvluationBaseFragment.newInstance(2, action));
        fragments.add(ProductEvluationBaseFragment.newInstance(8, action));
//        fragments.add(ProductEvluationBaseFragment.newInstance(7, action));
    }

    protected void initRightMenu(){
        cacheManager = new FileCacheManager();
        rightMenuCachePath = mContext.getCacheDir() + "/productEvaluationRightMenu_" + action + ".dat";
        sortBtn.setOnClickListener(this);
        rightMenuRv.setHasFixedSize(true);
        rightMenuRv.setLayoutManager(new LinearLayoutManager(mContext));
        rightMenuRv.addItemDecoration(new JpDiver(mContext));
        menuModelList = new ArrayList<>();
        rightMenuAdapter = new ProductInterfaceRightMenuAdapter(mContext, menuModelList);
        rightMenuRv.setAdapter(rightMenuAdapter);
        rightMenuAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                if(position == rightMenuAdapter.getSelectedPosition())
                    return;
                rightMenuAdapter.setSelectedPosition(position);
                rightMenuAdapter.notifyDataSetChanged();
                drawerLayout.closeDrawer(rightMenu);

                String tagId = menuModelList.get(rightMenuAdapter.getSelectedPosition()).getId();
                if(tagId == null)
                    topName.setText(getIntent().getStringExtra("name"));
                else
                    topName.setText(menuModelList.get(rightMenuAdapter.getSelectedPosition()).getName());
                for(Fragment fragment : fragments)
                    ((ProductEvluationBaseFragment)fragment).autoRefresh(tagId);
            }
        });
        readRightMenuData();
    }

    private void readRightMenuData(){
        Observable.create(new Observable.OnSubscribe<List<ProductUIMenuModel>>() {
            @Override
            public void call(Subscriber<? super List<ProductUIMenuModel>> subscriber) {
                List<ProductUIMenuModel> data = (List<ProductUIMenuModel>) cacheManager.readObject(rightMenuCachePath);
                subscriber.onNext(data);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<List<ProductUIMenuModel>>() {
            @Override
            public void onCompleted() {
                getRightMenuData();
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<ProductUIMenuModel> data) {
                if(data != null) {
                    menuModelList = data;
                    rightMenuAdapter.updateAdapter(menuModelList);
                }
                onCompleted();
            }
        });
    }

    private void getRightMenuData(){
        JsonObject param = new JsonObject();
        param.addProperty("action", action);
        HttpHelper.getInstance(mContext).catalogTree(param, 0x01, new ResultSubscriber.OnResultListener() {
            @Override
            public void onStart(int requestType) {}
            @Override
            public void onCompleted(int requestType) {}
            @Override
            public void onError(int requestType) {}
            @Override
            public void onNext(IModel data, int requestType) {
                menuModelList = data.getList(ProductUIMenuModel.class);
                if(menuModelList == null)
                    menuModelList = new ArrayList<>();
                ProductUIMenuModel model = new ProductUIMenuModel();
                model.setName("全部");
                menuModelList.add(0, model);
                rightMenuAdapter.updateAdapter(menuModelList);
                saveCache(menuModelList);
            }
        });
    }

    protected void initTabLayout(){
        tabView.setTabItems("推荐", "最热", "私有");
        tabView.setupWithViewPager(viewPager);
    }

    protected void initTitleBar(){
        topName.setText(getIntent().getStringExtra("name"));
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        rightIcon.setVisibility(View.VISIBLE);
        leftIcon.setOnClickListener(this);
        rightIcon.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.icon_left:
                onBackPressed();
                break;
            case R.id.icon_serach:
                gotoSearch();
                break;
            case R.id.sort_btn:
                drawerLayout.openDrawer(rightMenu);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if(drawerLayout.isDrawerOpen(rightMenu))
            drawerLayout.closeDrawer(rightMenu);
        else
            super.onBackPressed();
    }

    protected void gotoSearch(){
        SearchSimpleActivity.gotoSearch(mContext, recommendAction, action, null, false);
    }

    private void saveCache(final Object data){
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(data, rightMenuCachePath);
            }
        }).start();
    }
}
